<?php
/**
 * @author Lukas Normantas
 */
class Blog_Model_PostGateway
{
    /**    
     * @var Zend_Form
     */
    protected $_form = null;

    public function getForm($post_id = null){
        if ($this->_form == null){
            $this->_form = new Blog_Form_PostForm();
        }
        if ($post_id) {
            $blogPost = Doctrine::getTable('Blog_Model_Post')->find($post_id);
            $this->_form->setDefaults($blogPost->toArray());
        }
        return $this->_form;
    }

    public function add($data)
    {
        $form = $this->getForm();
        if ($form->isValid( $data )){
            $blogPost = new Blog_Model_Post();
            $blogPost->fromArray($form->getValues());
            $blogPost->author_id = Zend_Auth::getInstance()->getIdentity()->getUserId();
            $blogPost->save();
            return true;
        }
        return false;
    }

    public function edit($data, $post_id)
    {
        $form = $this->getForm();
        if ($form->isValid( $data )){
            $blogPost = Doctrine::getTable('Blog_Post')->find($post_id);
            $blogPost->fromArray($form->getValues());
            //$blogPost->author_id = Zend_Auth::getInstance()->getIdentity()->getUserId();
            $blogPost->save();
            return true;
        }
        return false;

    }

    public function getPostData($post_id)
    {
        $q = Doctrine_Query::create()
            ->select('')
            ->from('Blog_Model_Post p')
            ->leftJoin('p.Author a')
            ->leftJoin('p.Comments c')
            ->where('p.id = ?')
            ->orderBy('c.created_at')
            ->limit(1);
        return $q->fetchOne(array($post_id), Doctrine::HYDRATE_ARRAY);
    }

    public function getPager($currentPage)
    {
        $resultsPerPage = 2;

        return new Doctrine_Pager(
            Doctrine_Query::create()
                ->from( 'Blog_Model_Post p' )
                ->leftJoin( 'p.Author u' )
                ->where( 'p.status = ?', 'published' )
                ->orderBy( 'p.created_at DESC' ),
                $currentPage,
                $resultsPerPage
        );       
    }

    public function getAdminPager($currentPage)
    {
        $resultsPerPage = 4;

        return new Doctrine_Pager(
            Doctrine_Query::create()
                ->from( 'Blog_Model_Post p' )
                ->leftJoin( 'p.Author u' )
                ->orderBy( 'p.created_at DESC, u.first_name DESC'  ),
                $currentPage,
                $resultsPerPage
        );
    }

    public function deletePosts($ids)
    {
        $q = Doctrine_Query::create()
            ->delete('Blog_Model_Post p')
            ->where('p.id IN ?', array($ids));
        return $q->execute();
    }
}

